package org.jeecg.modules.rental.mq.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.rental.entity.RentalAccountCoupon;
import org.jeecg.modules.rental.entity.RentalCouponOrder;
import org.jeecg.modules.rental.entity.RentalCouponOrderDetail;
import org.jeecg.modules.rental.mapper.RentalCouponOrderMapper;
import org.jeecg.modules.rental.service.IRentalCouponOrderDetailService;
import org.jeecg.modules.rental.service.IRentalAccountCouponService;
import org.jeecg.modules.rental.util.OrderSnUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author by sean
 * @desc: 处理支付卡券订单
 * @since 2024-10-14 星期一 14:41:28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BuyCouponOrderService {

    private final OrderSnUtil orderSnUtil;
    private final RentalCouponOrderMapper rentalCouponOrderMapper;
    private final IRentalCouponOrderDetailService couponOrderDetailService;
    private final IRentalAccountCouponService rentalAccountCouponService;

    @Transactional
    public void processOrder(Long orderId, BigDecimal payAmount, LocalDateTime payTime) {
        log.debug("业务处理开始：{}", orderId);
        RentalCouponOrder couponOrder = rentalCouponOrderMapper.selectById(orderId);
        if (couponOrder == null) {
            log.error("订单号不存在: {}", orderId);
            return;
        }

        // 幂等性校验：检查订单状态
        if (couponOrder.getOrderStatus() != 1) {
            log.warn("订单 {} 状态已更新为 {}，跳过处理", orderId, couponOrder.getOrderStatus());
            return;
        }

        // 获取订单金额和 openid
        BigDecimal orderPayAmount = couponOrder.getPayAmount();
        // 金额校验
        if (orderPayAmount.compareTo(payAmount) != 0) {
            log.error("订单金额不匹配: orderAmount={}, chargeAmount={}", orderPayAmount, payAmount);
            //return;
        }

        // 更新优惠券订单状态
        couponOrder.setOrderStatus(2); // 订单状态 2-已支付
        couponOrder.setPayTime(payTime);
        rentalCouponOrderMapper.updateById(couponOrder);

        List<RentalCouponOrderDetail> detailList = couponOrderDetailService
                .list(new QueryWrapper<RentalCouponOrderDetail>()
                        .eq("order_id", couponOrder.getId()));

        List<RentalAccountCoupon> accountCouponList = new ArrayList<RentalAccountCoupon>();
        detailList.forEach(item->{
            // 添加用户卡券
            RentalAccountCoupon accountCoupon = new RentalAccountCoupon();
            String couponCode = orderSnUtil.getCouponCode(item.getCategoryCode());
            accountCoupon.setOrderId(orderId);
            accountCoupon.setCouponCategory(item.getCategoryCode());
            accountCoupon.setCouponCode(couponCode);
            accountCoupon.setAccountId(couponOrder.getAccountId());
            accountCoupon.setConfigId(item.getCouponConfigId());
            accountCoupon.setConfigName(item.getConfigName());
            accountCoupon.setCouponColor(item.getColor());
            accountCoupon.setMinAmount(item.getMinAmount());
            accountCoupon.setFaceValue(item.getFaceValue());
            accountCoupon.setReceiveTime(LocalDateTime.now());
            accountCoupon.setExpiryDate(LocalDate.now().plusDays(item.getValidDays()));
            accountCoupon.setStatus("0");
            accountCoupon.setSysOrgCode(item.getSysOrgCode());
            accountCouponList.add(accountCoupon);
        });
        rentalAccountCouponService.saveOrUpdateBatch(accountCouponList);
        log.info("step_4:订单支付成功: {}", orderId);
    }
}
